import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/globalConfig.dart';
import 'package:gd_assistant/model/packageModel.dart';
import 'package:gd_assistant/model/patientModel.dart';
import 'package:gd_assistant/model/userModel.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/publicView.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/page/user/patientInfoPage.dart';
import 'package:gd_assistant/util/customRoute.dart';

class selectPatientPage extends StatefulWidget {
  selectPatientPage(PackageModel this.package, String this.customerId, {Key key, Function this.callBack}):super(key: key);
  
  PackageModel package;
  String customerId;
  Function callBack;
  @override
  _selectPatientPageState createState() => _selectPatientPageState();
}

class _selectPatientPageState extends State<selectPatientPage> {
  bool isDark = false;
  List<PatientModel> patients = [];
  List<Items> assistants = [];
  int selectIndex = 0;
  int avartIndex = 0;
  @override
  void initState() {
    super.initState();
    loadData();
  }

  loadData() async {
    var pat = await apiHandler.getPatientList(widget.customerId);
    if (pat != null) {
      setState(() {
        patients = pat;
      });
    }
    UserModel res = await apiHandler.getServPackageAssistant(widget.package.doctor.sId);
    setState(() {
      assistants = res.items;
    });
  }

  setUpPatientInfo() async {
    TostUtil.showLoading(context, "就诊信息提交中...");
    PatientModel patient = patients[selectIndex];
    Items assistant = assistants[avartIndex];
    String isNew = patient.isNewPatient == "1" ? patient.isNewPatient : "0";
    dynamic cb = await apiHandler.postNewPatientInfo(assistant.sId,patient.sId,widget.package.order.orderId, isNew);
    
    
    if (cb != null) {
      TostUtil.show("完善就诊人成功");
    }
    TostUtil.removeLoading(context);
    Navigator.pop(context);
    if (widget.callBack != null) {
      widget.callBack();
    }
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    final EdgeInsets padding = MediaQuery.of(context).padding;
    return Scaffold(
      appBar: AppBar(
        title: Text("选择就诊人"),
        elevation: 0
      ),
      body: Container(
        color: Colours.bg_gray,
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: ListView.builder(
                itemBuilder: (context, index) {
                  if (index==(patients.length + 1)) {
                    return Container(
                      color: Colors.white,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(left: 16,top: 12),
                            child: Text("选择助理",style: TextStyle(fontSize: 17,fontWeight: FontWeight.w500)),
                          ),
                          Container(
                            height: 120,
                            child:  ListView.builder(
                              scrollDirection: Axis.horizontal,
                              itemBuilder: (context, index){
                                Items assitant = assistants[index];
                                return GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      avartIndex = index;
                                    });
                                  },
                                  child: Container(
                                    width: 80,
                                    height: 140,
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: <Widget>[
                                        Container(
                                           decoration: BoxDecoration(
                                            border: Border.all(color: avartIndex == index ? Colors.blue : Colors.white, width: 1.5),
                                            borderRadius: BorderRadius.circular((34)),
                                          ),
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.circular(30),
                                            child: ExtendedImage.network(
                                              GlobalConfig.qiNiuUri + (assitant.avatar.length > 0 ? assitant.avatar : "head.png"),
                                              width: 60,
                                              height: 60,
                                            ),
                                          )
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(top: 10,left: 5,right: 5),
                                          child: Text(assitant.name,style: TextStyle(color: avartIndex == index ? Colors.blue : Colors.black, fontWeight: avartIndex == index ? FontWeight.w600 : FontWeight.w400),maxLines: 1),
                                        )
                                      ],
                                    ),
                                  ),
                                );
                              },
                              itemCount: assistants.length),
                          )
                        ],
                      ),
                    );
                  }
                  if (index==patients.length) {
                    return GestureDetector(
                      onTap: (){
                        Navigator.of(context).push(
                          CustomRoute(patientInfoPage(userId: widget.customerId, isNew: true, callBack: (PatientModel pt){
                            //添加新的就诊人成功
                            patients.insert(0,pt);
                            setState(() {});
                          }))
                        );  
                      },
                      child: Container(
                        height: 60,
                        alignment: Alignment.center,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Icon(Icons.add_circle,color: Colors.blue),
                            Text("新增就诊人",style: TextStyle(fontSize: 18,fontWeight: FontWeight.w500))
                          ],
                        )
                      ),
                    );
                  }

                  PatientModel patient = patients[index];
                  return GestureDetector(
                    onTap: (){
                      setState(() {
                        selectIndex = index;
                      });
                    },
                    child: Container(
                      height: 60,
                      color: Colors.white,
                      child: Row(
                        children: <Widget>[
                          Container(
                            alignment: Alignment.center,
                            width: (MediaQuery.of(context).size.width - 80)/3,
                            child: Text(patient.name, style: TextStyle(fontSize: 16),maxLines: 1,overflow: TextOverflow.ellipsis),
                          ),
                          Container(
                            alignment: Alignment.center,
                            width: (MediaQuery.of(context).size.width - 80)/3 - 60,
                            child: Text(patient.sex, style: TextStyle(fontSize: 16),maxLines: 1,overflow: TextOverflow.ellipsis),
                          ),
                          Container(
                            alignment: Alignment.center,
                            width: (MediaQuery.of(context).size.width - 80)/3 + 60,
                            child: Text(patient.sphoneNum, style: TextStyle(fontSize: 14),maxLines: 1,overflow: TextOverflow.ellipsis),
                          ),
                          Container(
                            color: isDark ? Colours.dark_bg_color : Colors.white,
                            width: 80,
                            child: Center(
                              child: selectIndex == index ? Icon(Icons.check_box, size: 16, color: Colors.blue,): Icon(Icons.check_box_outline_blank, size: 16)
                            ),
                          ),
                        ],
                    ),
                  ),
                  );
                },
                itemCount: patients.length + 2,
              )
            ),
            Container(
              padding: EdgeInsets.only(bottom: padding.bottom),
              width: double.infinity,
              height: 65 + padding.bottom,
              color: isDark ? Colours.dark_bg_color : Colors.white,
              child: ZLButton(
                title: "完成",
                onTap: (){
                  setUpPatientInfo();
                } 
              )
            ),
          ],
        )
      )
    );
  }
}